package model

import com.alibaba.fastjson.JSON
import com.github.thomasnield.rxkotlinfx.observeOnFx
import entity.MyContract
import entity.PropertyValue
import entity.SysProperties
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
import presenter.MainPresenter
import tornadofx.observable
import util.MyEncodeUtil
import java.io.File
import java.io.FileReader
import java.io.FileWriter

class SysPropertiesModel(val mainPresenter: MainPresenter) {

    fun getSysPropertiesFromFile(): SysProperties {
        val file = File(MyContract.PROPERTIES_FILE_NAME)
        return if(file.exists()) {
            val reader = FileReader(file)
            val jsonStr = reader.readText()
            reader.close()

            JSON.parseObject(jsonStr, SysProperties::class.javaObjectType)
        } else {
            setSysPropertiesToFile(PropertyValue.defaultProperties)
            getSysPropertiesFromFile()
        }
    }

    private fun setSysPropertiesToFile(sysProperties: SysProperties) {
        val jsons = JSON.toJSONString(sysProperties)

        val writer = FileWriter(MyContract.PROPERTIES_FILE_NAME, false)
        writer.write(jsons)
        writer.flush()
        writer.close()
    }

    fun saveProperties(sysProperties: SysProperties) {
        Observable.just(sysProperties)
                .subscribeOn(Schedulers.io())
                .map { if (sysProperties.defaultMode == PropertyValue.ModeValue.VALUE_EDIT_MODE) sysProperties.copy(defaultMode = PropertyValue.ModeValue.VALUE_NORMAL_MODE) else sysProperties }
                .subscribe {
                    setSysPropertiesToFile(it)
                }
    }
}